﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DunSilverlight.Web.Comm;
using DunLibrary.User;
using System.ServiceModel.Activation;
using NHibernate;
using DunSilverlight.Web.Serializable;
using System.Text.RegularExpressions;

namespace DunSilverlight.Web.UserWcf
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“UserService”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class UserService : BaseService<User>, IUserService
    {
        /// <summary>
        /// 验证登录用户
        /// 如果成功返回用户及关联的组织机构，否则给出错误信息。
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string Login(string userName, string password)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    DunLibrary.User.User u = sess.CreateQuery("from User where Name=:uName and Password=:Pwd").SetParameter<string>("uName", userName).SetParameter<string>("Pwd", password).UniqueResult<User>();

                    if (u != null)
                    {
                        //加载用户所属机构和角色
                        NHibernateUtil.Initialize(u.Organization);
                        NHibernateUtil.Initialize(u.Role);
                        string json = JsonSerializerHelper.EntityToJson(u);
                        return PackJsonResult("true", json, string.Empty);
                    }
                    else
                    {
                        return this.PackJsonResult("false", "null", "用户名或密码不正确");
                    }
                }
                catch (Exception ex)
                {
                    return this.PackJsonResult("false", "null", ex.Message);
                }

            }
        }


        public override string SaveOrUpdate(string json)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                ITransaction tx = null;

                User entity = JsonSerializerHelper.JsonToEntity<User>(json);

                try
                {
                    tx = sess.BeginTransaction();

                    //如果新增判断用户是否存在
                    if (entity.Id == 0)
                    {
                        var oldUser = sess.CreateQuery("From User where Name = '" + entity.Name + "'").List<User>().FirstOrDefault();
                        if (oldUser != null)
                        {
                            return PackJsonResult("false", Newtonsoft.Json.JsonConvert.Null, "该用户已经存在");
                        }
                    }

                    //验证密码规则，8位以上数字字母混合
                    if(!(Regex.IsMatch(entity.Password,"^[a-zA-Z0-9]{8,}$",RegexOptions.IgnoreCase) //8位以上数字或字母
                        && !Regex.IsMatch(entity.Password,"^[a-zA-Z]{8,}$",RegexOptions.IgnoreCase) //不能全部为字母
                        && !Regex.IsMatch(entity.Password,"^[0-9]{8,}$",RegexOptions.IgnoreCase))   //不能全部为数字
                        )
                    {
                        return PackJsonResult("false", Newtonsoft.Json.JsonConvert.Null, "密码必须8位以上，并同时包含数字和字母!");
                    }

                    sess.SaveOrUpdate(entity);
                    tx.Commit();
                    return PackJsonResult("true", JsonSerializerHelper.EntityToJson(entity), string.Empty);
                }
                catch (Exception ex)
                {
                    if (tx != null && tx.IsActive)
                        tx.Rollback();

                    return PackJsonResult("false", "0", ex.Message);
                }
            }
        }


        public virtual string GetUsers()
        {
            string hql = "from User where Name != 'admin'";
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    IList<User> ls = sess.CreateQuery(hql).List<User>();

                    if (ls.Count > 0 && ls[0] == null)
                        ls.RemoveAt(0);


                    string json = JsonSerializerHelper.EntityToJson(ls);

                    string s = PackJsonListResult("true", json, string.Empty, ls.Count);

                    return s;
                }
                catch (Exception ex)
                {
                    return PackJsonListResult("false", "[]", ex.Message, 0);
                }
            }
        }

        #region IUserService 成员

        #endregion
    }
}
